import { getStorage, removeStorage } from '@/utils/storage.js'
import { getInfo, logout } from "@/api/User.js";
import { defineStore } from "pinia";

const useUserStore = defineStore("user", {
    state: () => ({
        token: null,
        userInfo: null,
    }),
    actions: {
        getToken() {
          return getStorage("TOKEN");
        },
        getUserInfo() {
            return new Promise((resolve, reject) => {
                if (this.userInfo == null && this.getToken()) {
                  getInfo()
                    .then((res) => {
                      this.userInfo = res.data;
                      resolve(res);
                    })
                    .catch((error) => {
                      reject(error);
                    });
                } else {
                  resolve(this.userInfo || {});
                }
            });
        },
        logout() {
            return new Promise((resolve, reject) => {
                logout()
                    .then(() => {
                        this.token = "";
                        this.userInfo = {};
                        removeStorage("TOKEN");
                        removeStorage("REFRESH_TOKEN")
                        resolve();
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
    },
});

export default useUserStore;
